package com.example.demo;

import org.eclipse.jgit.api.CloneCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.IOException;

@Controller
public class JgiCon {

    @Value("${spring.cloud.config.server.git.uri}")
    String giturl;


    @Value("${spring.cloud.config.label}")
    String branch;

    @Value("${test.gitsavepath}")
    String targetPath;


    @RequestMapping("/hello")
    @ResponseBody
    public String testgit() throws IOException {
        cloneRepository2(giturl,branch,targetPath);


        return "url="+giturl+",branch="+branch+",targetPath="+targetPath;
    }

    private  void cloneRepository2(String url, String branch, String targetPath) throws IOException {
        File path =new File(targetPath);
        Git result = null;
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(path).readEnvironment().findGitDir().build();

        Git git = new Git(repository);
        CloneCommand clone = git.cloneRepository();
        clone.setDirectory(path).setURI(url);
        try {
           // UsernamePasswordCredentialsProvider user=new UsernamePasswordCredentialsProvider("jiang28555@gmail.com","password");
            //clone.setCredentialsProvider(user);
            clone.call();
        } catch (GitAPIException e) {
            e.printStackTrace();
        }
    }

    private  Git cloneRepository(String url, String branch, String targetPath) throws IOException {
        Git result = null;
        try {
            CloneCommand cloneCommand = Git.cloneRepository().setCloneSubmodules(true)
                    .setURI(url).setBranch(branch)
                    .setDirectory(new File(targetPath));
                    cloneCommand.setCloneSubmodules(true);

                    cloneCommand.setBare(false);

            result = cloneCommand.call();
        } catch (GitAPIException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) throws IOException {
        new JgiCon().cloneRepository("http://github.com/google/mathfu", "master", "D:/codebase");
        //cloneRepository("https://github.com/google/mathfu", "master", "D:/codebase");
    }
}
